<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>代码雨</title>
  </head>
  <link rel="stylesheet" type="text/css" href="../css/reset.css" />
  <style>
    canvas {
      width: 100%;
      height: 100%;
    }
  </style>

  <body>
    <canvas id="canvas"></canvas>
  </body>
  <script>
    /* 设计思路  nextChars记录开始位置*/

    // 获取 canvas 元素
    const cvs = document.getElementById("canvas"); //获取窗口尺寸
    const width = window.innerWidth * devicePixelRatio,
      height = window.innerHeight * devicePixelRatio; // 设置 canvas 尺寸为窗口尺寸
    cvs.width = width;
    cvs.height = height;
    // 获取绘制上下文
    const ctx = cvs.getContext("2d");
    // 字体大小
    const fontsize = 20 * devicePixelRatio;

    const columnWidth = fontsize;
    // 列数
    const columnCount = Math.floor(width / columnWidth);
    // 每一列下一个字符是第几个字符
    const nextChars = new Array(columnCount).fill(0);
    console.log("nextChars", nextChars);
    console.log("columnCount", columnCount, fontsize);

    function getRandomColor() {
      const fontColors = [
        "#33B5E5",
        "#0899CC",
        "#AA66CC",
        "#9933CC",
        "#99CC00",
        "#669900",
        "#FFBB33",
        "#FF8800",
        "#FF4444",
        "#CC0000",
      ];
      return fontColors[Math.floor(Math.random() * fontColors.length)];
    }

    function getRandomChar() {
      const str = `console.log("hello world")`;
      return str[Math.floor(Math.random() * str.length)];
    }

    // 西一排文字
    function draw() {
      ctx.fillStyle = "rgba(0,0,0,0.1)";
      ctx.fillRect(0, 0, width, height);
      for (let i = 0; i < columnCount; i++) {
        // ctx
        // 什么字符，什么颜色，字体大小、字体类型、什么位置 (x,y)
        const char = getRandomChar();
        ctx.fillStyle = getRandomColor();
        ctx.font = `${fontsize}px "Roboto Mono"`;
        const x = columnWidth * i;
        const index = nextChars[i];
        const y = (index + 1) * fontsize;
        ctx.fillText(char, x, y);
        console.log(char, x, y);
        if (y > height || Math.random() > 0.99) {
          nextChars[i] = 0;
        }
        nextChars[i]++;
      }
    }
    draw();
    setInterval(draw, 50);
  </script>
</html>
